package com.jrmf.redenvelopes.order.controller;

import com.jrmf.redenvelopes.order.dao.JdpaySignPayMapper;
import com.jrmf.redenvelopes.order.util.DateUtil;
import com.jrmf.redenvelopes.order.util.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

@RestController
@RequestMapping("accountExportController")
@Api(value = "accountExportController", description = "对账结果导出")
public class AccountExportController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private JdpaySignPayMapper jdpaySignPayMapper;

    private static final String[] TITLE = new String[]{"结果类型","交易时间","对照id","交易金额","支付状态码","支付响应码","支付响应信息"};
    //private static final String SHEET_NAME = "page1";


    @ApiOperation(value = "入金对账结果导出",produces="application/octet-stream")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "对账日期", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "第三方支付平台", required = true, dataType = "String", paramType = "query"),
    })
    @GetMapping(value = "/accountExport/page/thread")
    @ResponseBody
    public void exportSXSSFWorkbookByPageThread(HttpServletResponse response, @RequestParam String data,@RequestParam String type )  {
        long start = System.currentTimeMillis();
        short thirdpartyPaytype = 0;
        String accountData = "";
        String fileName = "";
        Map<String ,Object> param =new HashMap<>();
        if (null!=data && !"".equals(data)){
            accountData =data;
        }
        else {//默认对前一天的
            accountData = DateUtil.dateToStr(DateUtil.getYesterday(),"yyyyMMdd");
        }
        if (null!=type&&!"".equals(type)){
            try {
                thirdpartyPaytype = (short) (int)Integer.valueOf(type);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        else {
            thirdpartyPaytype =(short) 1;//默认先锋
        }
        if (thirdpartyPaytype==(short) 1){
            fileName =accountData+"xf.xlsx";
            param.put("tradeNode","QP_UCFPAY");
        }
        else if (thirdpartyPaytype==(short) 2){
            fileName=accountData+"kb.xlsx";
            param.put("tradeNode","QP_YACOLPAY");
        }
        else {
            fileName =accountData+"unknown.xlsx";
            param.put("tradeNode","QP_UCFPAY");
        }
        String[][] content = buildContent(65536);

        Map<String ,Object> map =new HashMap<>();

        param.put("dateTime",accountData);
        param.put("thirdpartyPaytype",thirdpartyPaytype);
        List<Map<String,Object>> list1 =jdpaySignPayMapper.accountThird2Mf(param);
        logger.info(String.valueOf(list1.size()));
        List<Map<String,Object>> list2 =jdpaySignPayMapper.accountMf2Third(param);
        logger.info(String.valueOf(list2.size()));
        List<Map<String,Object>> list3 =jdpaySignPayMapper.accountThirdwithMf(param);
        logger.info(String.valueOf(list3.size()));
        List<Map<String,Object>> finalList =new ArrayList<>();
        if (list1.size()>0){
            finalList.addAll(list1);
        }
        if (list2.size()>0){
            finalList.addAll(list2);
        }
        if (list3.size()>0){
            finalList.addAll(list3);
        }

        //读取数据

        SXSSFWorkbook wb = ExcelUtil.getSXSSFWorkbookByPageThread(TITLE, content,finalList);

        long millis = System.currentTimeMillis() - start;
        long second = millis / 1000;
        logger.info("导出"  +finalList.size()+ "条数据，花费：" + second + "s/ " );
        writeAndClose(response, fileName, wb);
        wb.dispose();
    }

    /**
     * 构建内容
     *
     * @param num
     * @return
     */
    private String[][] buildContent(Integer num) {
        //查询数据，返回list<Map>
        String[][] content = new String[num][4];
        for (int i = 0; i < content.length; i++) {
            content[i][0] = "测试1";
            content[i][1] = "厕所2";
            content[i][2] = "测试3";
            content[i][3] = "测试4";
        }
        return content;
    }

    private void writeAndClose(HttpServletResponse response, String fileName, Workbook wb) {
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //response.setContentType("application/octet-stream;charset=UTF-8");
            //response.setContentType("application/vnd..ms-excel;charset=UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


}
